#include "add.h"
#include "ui_add.h"




Add::Add(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Add)
{
    ui->setupUi(this);
    qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "7777");

    _myChannel = new myChannel(this);
    _mItemModel =new QStandardItemModel(this);

    QWebChannel* web_channel = new QWebChannel(this);
    web_channel->registerObject("qtChannel",_myChannel);
    ui->webengineview->page()->setWebChannel(web_channel);
    ui->webengineview->load(QUrl("qrc:/smap/mymap_ba.html"));

    QObject::connect(ui->pushButton_setcity, &QPushButton::clicked, this, &Add::setCity);
    QObject::connect(_myChannel, &myChannel::setCityLable, [this](QString city) {
        ui->label_city->setText(QString::fromLocal8Bit("city:") + city);
    });
    QObject::connect(_myChannel,&myChannel::sendAutocomplete,this,&Add::setAutoComplete);
    QObject::connect(ui->submit ,&QPushButton::clicked,this,&Add::savemess);
}


void Add::setCity()
{
    QString city = ui->lineEdit_setcity->text().trimmed();
    if (city.size() == 0)
    {
        QMessageBox::warning(this,"Warning","please enter a city!");
        return;
    }
    _myChannel->setCity(city);
}

void Add::setAutoComplete(QJsonObject result)
{
    std::cout<<"in setAuto"<<std::endl;
    _mItemModel->clear();
    if(!(result.contains("tips")&&result["tips"].isArray()))
    {
        return;
    }

    for(auto e:result["tips"].toArray())
    {
        QJsonObject d=e.toObject();
        if(d.contains("name"))
        {
            QString s=d["name"].toString();
            if(s.size()>0)
            {
                QStandardItem * item=new QStandardItem(s);
                _mItemModel->appendRow(item);
                std::cout<<s.toStdString()<<std::endl;
            }
        }
    }

}

void Add::savemess()
{
    emit closeBox();
    QFile file("basic.txt");
    file.open(QIODevice::Append);//以添加方式打开文件
    QDataStream write(&file);
    write<<ui->name->text()<<ui->address->text();
    file.close();
    this->close();
}

QString Add::getname()
{
    return ui->name->text();
}

QString Add::getaddress(){return ui->address->text();}

